var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var YjxBaseModel = require('./YjxBaseModel');
var CONFIG = require('../../config');


var YjxActUserProductModel = function (obj) {
    YjxBaseModel.call(this,obj);

    // `aup_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '作品id',
    // `user_id` bigint(20) NOT NULL COMMENT '用户id',
    // `act_id` bigint(20) NOT NULL COMMENT '活动id',
    // `type` int(3) NOT NULL DEFAULT '10' COMMENT '活动分类: 10:推广有奖活动',
    // `reward_amt` bigint(20) NOT NULL COMMENT '奖励数量',
    // `unit` varchar(20) DEFAULT NULL COMMENT '奖励单位',
    // `data1` text NOT NULL COMMENT '数据1',
    // `data2` text NOT NULL COMMENT '数据2',
    // `data3` text NOT NULL COMMENT '数据3',
    // `data4` text NOT NULL COMMENT '数据4',
    // `data5` text NOT NULL COMMENT '数据5',
    // `theme_img` text COMMENT '作品主图',
    // `images` text COMMENT '作品详细图,JSON数组',
    // `url` text COMMENT '作品链接',
    // `state` int(3) NOT NULL DEFAULT '10' COMMENT '作品状态: 10新建, 20评审中, 30通过',
    // `desc` text COMMENT '用户作品描述',
    // `note` text COMMENT '审核备注',
    // `create_time` datetime NOT NULL,
    // `update_time` datetime NOT NULL,
    // `update_by` varchar(50) DEFAULT NULL,
    // `del_flg` int(1) NOT NULL DEFAULT '0',

};

YjxActUserProductModel.prototype = new YjxBaseModel();

// 取得表名
YjxActUserProductModel.prototype.getTableName = function(){
    return 'yjx_act_user_product';
};
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
YjxActUserProductModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'aup_id='+this.aup_id;
};

/**
 * 获取活动作品列表的 sql
 *
 * @author 王俊
 * @date 2018-06-08
 *
 * @param {Object} options 参数
 * @param {Number} [options.beForCnt] 是否用于获取个数, 默认不是
 * @param {Number} options.activityId 参数
 * @param {Number} [options.userId] 参数(是否限制用户, 若限制用户则不再限制作品状态)
 * @param {Number} [options.pageNum] 页码
 * @param {Number} [options.pageSize] 页容量
 *
 * @return sql 对应的 sql
 *
 */
function sql_getActivityProductList(options) {

    var sql = '';
    if(options.beForCnt) {
        sql += ' SELECT count(0) as count';

    } else {
        sql +=
            '   SELECT yaup.*, ' +
            '       CASE WHEN length(yaup.theme_img_cust) > 7 THEN yaup.theme_img_cust ' +
            '            ELSE yaup.theme_img ' +
            '       END AS thumb, ' +
            '           CASE WHEN yaup.rank = 0 THEN 1 ELSE 0 END as valid_rank, ' +
            '           yas.platform_type ';
    }
    sql +=
        '    FROM yjx.yjx_act_user_product yaup, ' +
        '         yjx.yjx_act_setting yas, ' +
        '         yjx.yjx_activity ya ' +
        '    WHERE yaup.del_flg = 0 ' +
        '      AND yaup.act_id= ya.act_id ' +
        '      AND ya.act_id = ' + options.activityId +
        '      AND ya.del_flg = 0 ' +
        '      AND yas.del_flg = 0 ' +
        '      AND yas.as_id = ya.as_id';
    if(options.userId) {
        sql += '      AND yaup.user_id = ' + options.userId;
    } else {
        sql += '      AND yaup.state = 30 ';
    }
    if(!options.beForCnt) {
        sql += options.userId ? ' ORDER BY yaup.create_time DESC ' :  ' ORDER BY valid_rank, yaup.rank ';
    }

    if(!options.beForCnt){
        if (typeof options.pageNum !== 'undefined' && options.pageNum !== null &&
            typeof options.pageSize !== 'undefined' && options.pageSize !== null) {
            var skipCnt = Number(options.pageNum || '0') * Number(options.pageSize || '0');
            sql += " LIMIT " + skipCnt + "," + Number(options.pageSize || '0');
        }
    }
    return sql;
}


/**
 * 获取活动作品列表
 *
 * @author 王俊
 * @date 2018-06-08
 *
 * @param {Object} options 参数
 * @param {Number} options.activityId 参数
 * @param {Number} [options.userId] 参数(是否限制用户, 若限制用户则不再限制作品状态)
 * @param {Number} options.pageNum 页码
 * @param {Number} options.pageSize 页容量
 *
 * @param {Function} callback 回调函数
 */
YjxActUserProductModel.prototype.getActivityProductList = function (options, callback) {

    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getActivityProductList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getActivityProductList(options);
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr) {
                console.log('YjxActUserProductModel.prototype.getActivityProductList queryErr: ' + queryErr);
            }
            // 回调
            callback(queryErr, results);
        });
    });
};
/**
 * 获取活动作品列表的总个数
 *
 * @author 王俊
 * @date 2018-06-08
 *
 * @param {Object} options 参数
 * @param {Number} options.activityId 活动 id
 * @param {Number} [options.userId] 用户 id
 * @param {Function} callback 回调函数
 *
 */
YjxActUserProductModel.prototype.getActivityProductListCnt = function (options, callback) {
    options.beForCnt = true;
    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getActivityProductList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getActivityProductList(options);
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                console.log('YjxActUserProductModel.prototype.getActivityProductList queryErr: ' + queryErr);
                return callback(queryErr || '查询失败');
            }
            // 回调
            callback(queryErr, results[0].count);
        });
    });
};


//***************************************************************************************************************
/**
 * 获取活动作品列表sql
 *
 * @param bForCnt  标记是否需要分页
 * @param {Object} param  筛选参数列表
 * @param {Number} param.pageNum  页码
 * @param {Number} param.pageSize  页容量
 * @param {Number} param.state  作品状态
 * @param {Array}  param.findStates  作品状态数组[10新建, 20评审中, 30通过, 40不通过]
 * @param {Number} param.actId  活动id
 * @param {Number} param.aupId  活动作品id
 * @param {Number} param.userId  用户id
 * @param {Number} param.orgId  组织id(如网红公司)
 * @param {String} param.mobile  用户手机号
 * @returns {string}
 */
function sql_getActList_2(bForCnt,param) {

    var sql = '';
    if(bForCnt) {
        sql += " SELECT COUNT(aup.aup_id) AS `count` ";
    } else  {
        sql += " SELECT aup.* " +
            " ,u.nickname, tpu.field1 AS mobile " +
            " ,ya.title,ya.state AS act_state,ya.act_no " +
            " ,DATE_FORMAT(aup.create_time, '%Y/%m/%d %H:%i:%S') AS fmt_create_time " +
            " ,DATE_FORMAT(aup.update_time, '%Y/%m/%d %H:%i:%S') AS fmt_update_time ";
    }
    sql +=  " FROM yjx.yjx_act_user_product aup " +
        " LEFT JOIN yjx.yjx_user u" +
        " 	ON u.user_id=aup.user_id AND u.del_flg=0 " +
        " LEFT JOIN yjx.yjx_third_party_user tpu " +
        " 	ON tpu.user_id=u.user_id AND tpu.account_type=10 AND tpu.del_flg=0 " +
        " LEFT JOIN yjx.yjx_activity ya " +
        " 	ON ya.del_flg = 0 AND ya.act_id = aup.act_id " +
        " WHERE aup.del_flg = 0 ";

    if(param.actId && param.actId>0) {
        sql += " 	and aup.act_id = "+param.actId;
    }
    if(param.aupId && param.aupId>0) {
        sql += " 	and aup.aup_id = "+param.aupId;
    }
    if(param.state && param.state>0) {
        sql += " 	and aup.state = "+param.state;
    }
    if(param.findStates && param.findStates.length>0) {
        sql += " 	and aup.state IN ("+(param.findStates.join(','))+") ";
    }
    if(param.mobile && (param.mobile||'').length>0) {
        sql += " 	AND tpu.field1 like CONCAT('%','" +param.mobile+ "','%') ";
    }
    if(param.orgId && param.orgId>0) {
        sql += " 	and aup.org_id = "+param.orgId;
    }
    if(param.userId && param.userId>0) {
        sql += " 	and aup.user_id = "+param.userId;
    }

    sql += " ORDER BY aup.update_time DESC " ;
    if (!bForCnt) {
        if (typeof param.pageNum !== 'undefined' && param.pageNum !== null &&
            typeof param.pageSize !== 'undefined' && param.pageSize !== null)
        {
            var skipCnt = Number(param.pageNum||'0') * Number(param.pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(param.pageSize||'0');
        }
    }
    return sql;
}
// 获取活动作品列表Cnt
YjxActUserProductModel.prototype.getActProdListCnt_2 = function (param,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActUserProductModel.js [getActProdListCnt_2] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getActList_2(true,param);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActUserProductModel.js [getActProdListCnt_2] queryErr' + queryErr)
            }
            return callback(queryErr, results[0].count);
        });
    })
};
// 获取活动作品列表信息
YjxActUserProductModel.prototype.getActProdList_2 = function (param,callback){
    pool.pool.getConnection(function (getConErr, connection) {
        if (getConErr) {
            console.log('YjxActUserProductModel.js [getActProdList_2] getConErr' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getActList_2(false,param);
        console.log(sql);
        connection.query(sql, function (queryErr, results) {
            connection.release();
            if (queryErr) {
                console.log('YjxActUserProductModel.js [getActProdList_2] queryErr' + queryErr)
            }
            return callback(queryErr, results);
        });
    })
};
//***************************************************************************************************************


/**
 * 查找数据库中是否有重复提交的作品
 *
 * @author jackLiu
 * @date   2018-6-8
 *
 * @param   callback 回调
 *             err:出错原因
 *             data:1表示有重复作品
 * @notice  依赖YjxActUserProductModel中tag字段，作为查找相同作品的依据
 * */
YjxActUserProductModel.prototype.haveSameProduct = function( callback){
    var urlKey = this.tag;
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.haveSameProduct getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =   '   select p.aup_id,    p.url,  p.theme_img '+
            '   from `yjx_act_user_product` p '+
            '   where p.`tag`="' + urlKey +'"' +
            '   and p.del_flg=0 '+
            '   and p.state IN (10,20,30) '+// 跳过【40不通过】的作品
            '   limit 0,1 ';
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.haveSameProduct Err: ' + error);
                return callback(error, null);
            }
            return callback(null, (results&&results.length>0)?1:0);
        })
    })


}

/**
 * 用户在某活动中提交的作品达到最大次数
 *
 * @author jackLiu
 * @date   2018-6-8
 *
 * @param   callback 回调
 *             err:出错原因
 *             data:1表示超过上限
 * @notice  依赖YjxActUserProductModel中 user_id/act_id 字段，作为查找的依据
 * */
YjxActUserProductModel.prototype.reachProductCountLimit  = function( callback){
    var user_id = this.user_id;
    var act_id = this.act_id;

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.reachProductCountLimit getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =
            ' select ( '+
            ' 	        select count(*)   '+
            ' 	        from yjx_act_user_product p '+
            ' 	        where p.user_id= '+user_id+
            ' 	        and p.act_id= '+act_id+
            ' 	        and p.del_flg=0 '+
            ' ) >= ( '+
            ' 	        select s.`product_limit`   '+
            ' 	        from `yjx_activity` a, '+
            ' 	        `yjx_act_setting` s '+
            ' 	        where a.`act_id`= '+act_id+
            ' 	        and a.`as_id`=s.`as_id` '+
            ' 	        and a.del_flg=0 '+
            ' 	        and s.del_flg=0 '+
            ' ) as result ';
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.reachProductCountLimit Err: ' + error);
                return callback(error, null);
            }
            return callback(null, (results&&results.length>0&& results[0].result==1)?1:0);
        })
    })
};

/**
 * 获取某活动下所有的作品 id
 *
 * @author 王俊
 * @date 2018-06-12
 *
 * @param {Object} options
 * @param {Number} options.activityId   活动 id
 * @param {Array} [options.productIds] 指定作品 id
 * @param {Number} [options.minReward] 限定最小获奖金额不传为0 单位分
 * @param {Function} callback 回调
 *                      error: 失败
 *                      results: [{aup_id : 1}]
 */
YjxActUserProductModel.prototype.getActivityProductIds = function (options, callback) {

    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =
            ' SELECT * ' +
            ' FROM yjx.yjx_act_user_product yaup ' +
            ' WHERE yaup.del_flg = 0 ' +
            '   AND yaup.act_id = ' + options.activityId ;
        if(options.productIds && options.productIds.length > 0) {
            sql += '   AND yaup.aup_id IN (' +options.productIds.join(',')+ ')';
        } else {
            sql += '   AND yaup.state = 30 ';
        }
        if(options.minReward){
            sql += '   AND yaup.reward_amt >=  ' + options.minReward;
        }
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.getActivityProductIds Err: ' + error);
            }
            return callback(error, results);
        })
    })
};


/*
* 获取活动的真实排名列表(sql 动态计算)
*
* @author 王俊
* @date 2018-06-13
*
* @param options
* @param {Number} options.activityId  活动 id
* @param {Function} callback 回调函数
* */
YjxActUserProductModel.prototype.getActivityProductRealRankList = function (options, callback) {
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.getActivityProductIds getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql =
            ' SELECT p.*, ' +
            '        p.points1 + p.points2 + points3 + points4 + points5 AS points ' +
            ' FROM ' +
            '   ( SELECT yaup.*, ' +
            '            yas.platform_type,' +
            '            if(yas.field1,yaup.data1 * yas.weight1, 0) AS points1, ' +
            '            if(yas.field1,yaup.data2 * yas.weight2, 0) AS points2, ' +
            '            if(yas.field1,yaup.data3 * yas.weight3, 0) AS points3, ' +
            '            if(yas.field1,yaup.data4 * yas.weight4, 0) AS points4, ' +
            '            if(yas.field1,yaup.data5 * yas.weight5, 0) AS points5 ' +
            '    FROM yjx.yjx_act_user_product yaup, ' +
            '         yjx.yjx_act_setting yas, ' +
            '         yjx.yjx_activity ya ' +
            '    WHERE yaup.del_flg = 0 ' +
            '      AND yaup.act_id= ya.act_id ' +
            '      AND ya.act_id = ' + options.activityId +
            '      AND ya.del_flg = 0 ' +
            '      AND yas.del_flg = 0 ' +
            '      AND yas.as_id = ya.as_id' +
            '      AND yaup.state = 30 ' +
            ' ) p ' +
            ' ORDER BY points DESC ';
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.getActivityProductRealRankList Err: ' + error);
            }
            return callback(error, results);
        })
    })
};

/**
 * 活动用户在该活动中的推荐码
 *
 * @author 毛凯
 * @date   2018-7-2
 *
 * @param userId 用户id
 * @param actId  活动id
 *
 * @param   callback 回调
 *             err:出错原因
 * */
YjxActUserProductModel.prototype.getUserCcodebyActIdAndUserId  = function(userId,actId,callback){
    pool.pool.getConnection(function(getConnectErr,connection) {
        if (getConnectErr) {
            console.log('YjxActUserProductModel.reachProductCountLimit getConnectErr: ' + getConnectErr);
            return callback(getConnectErr, null);
        }
        var sql ="SELECT  aup.c_code AS couponCode FROM yjx.yjx_act_user_product aup WHERE aup.user_id = "+userId+" AND aup.act_id = "+actId+" AND aup.del_flg = 0  AND aup.c_code IS NOT NULL LIMIT 0,1";
        console.log(sql);
        connection.query(sql, function (error, results) {
            connection.release();
            if (error) {
                console.log('YjxActUserProductModel.reachProductCountLimit Err: ' + error);
                return callback(error, null);
            }
            return callback(null,results);
        })
    })
};



/**
 * 通过条件获取活动作品列表sql(只提供冲顶大赛活动的作品)
 *
 * @param bForCnt  标记是否需要分页
 * @param {Object} param  筛选参数列表
 * @param {Number} param.pageNum  页码
 * @param {Number} param.pageSize  页容量
 * @param {String} param.state  作品状态
 * @param {String} param.actId  活动id
 * @param {Number} param.userId  用户id
 * @param {Number} param.orderBy  用户id
 * @returns {string}
 */
function sql_getActUserProductByParamList(bForCnt,param) {

    var sql = '';
    if(bForCnt) {
        sql += " SELECT COUNT(0) AS `count` ";
    } else  {
        sql +="	SELECT	" +
                "	  *	" ;
    }
    sql +="	FROM	" +
        "	  (SELECT	" +
        "	    yaup.aup_id AS id,	" +
        "       CASE WHEN length(yaup.theme_img_cust) > 7 THEN yaup.theme_img_cust " +
        "            ELSE yaup.theme_img " +
        "       END AS thumb, " +
        "	    IFNULL(yaup.url, '') AS url,	" +
        "	    IFNULL(yaup.video, '') AS video,	" +
        "	    yaup.state,	" +
        "	    yaup.note,	" +
        "	    yaup.desc,	" +
        "	    yaup.reward_amt AS rewardAmount,	" +
        "	    yaup.unit,	" +
        "	    yaup.data1 AS `like`,	" +
        "	    yaup.data2 AS `comment`,	" +
        "	    yaup.user_id,	" +
        "	    DATE_FORMAT(	" +
        "	      yaup.create_time,	" +
        "	      '%Y-%m-%d'	" +
        "	    ) AS create_time,	" +
        "	     yaup.create_time AS ctime,	" +
        "	    ya.act_id AS actId,	" +
        "	    ya.title AS actName,	" +
        " 	case when ya.state>30 then ya.state " +
        " 		 when ya.start_time>sysdate() then 10 " +
        " 	     when ya.end_time<=sysdate() then 30 " +
        " 	     else 20 " +
        " 	    end AS actState, " +
        "	    CASE	" +
        "	      WHEN yaup.rank = 0	" +
        "	      THEN 10000	" +
        "	      ELSE yaup.rank	" +
        "	    END AS rank,	" +
        "	    yas.platform_type	" +
        "	  FROM	" +
        "	    yjx.yjx_act_user_product yaup,	" +
        "	    yjx.yjx_act_setting yas,	" +
        "	    yjx.yjx_activity ya	" +
        "	  WHERE yaup.del_flg = 0	" +
        "	    AND yaup.act_id = ya.act_id	" +
        "	    AND ya.del_flg = 0	" +
        "	    AND yas.del_flg = 0	" +
        "	    AND yas.as_id = ya.as_id" +
        "       AND yaup.type = 10) res	" +
        "	WHERE 1 = 1	" ;
    if (param.actId){
       sql += "	  AND res.actId IN ("+param.actId+") " ;
    }
    if (param.state){
        sql += " AND res.state in ("+param.state+")	" ;
    }
    if (param.userId && param.userId > 0){
        sql += "  AND res.user_id = "+param.userId+" " ;
    }
    if (param.orderBy === 0){
        sql += "	ORDER BY res.rank ASC	" ;
    }
    if (param.orderBy === 1){
        sql +=   "	ORDER BY res.ctime DESC	" ;
    }
    if (!bForCnt) {
        if (typeof param.pageNum !== 'undefined' && param.pageNum !== null &&
            typeof param.pageSize !== 'undefined' && param.pageSize !== null)
        {
            var skipCnt = Number(param.pageNum||'0') * Number(param.pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(param.pageSize||'0');
        }
    }
    return sql;
}

/**
 * 获取活动作品列表(只提供冲顶大赛活动的作品)
 *
 * @author 毛凯
 * @date 2018-7-21
 *
 * @param {Object} options 参数
 * @param {Number} param.pageNum  页码
 * @param {Number} param.pageSize  页容量
 * @param {String} param.state  作品状态
 * @param {String} param.actId  活动id
 * @param {Number} param.userId  用户id
 * @param {Number} param.orderBy  用户id
 *
 * @param {Function} callback 回调函数
 */
YjxActUserProductModel.prototype.getActUserProductByParamList = function (options, callback) {

    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getActivityProductList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getActUserProductByParamList(false,options);
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr) {
                console.log('YjxActUserProductModel.prototype.getActivityProductList queryErr: ' + queryErr);
            }
            // 回调
            callback(queryErr, results);
        });
    });
};
/**
 * 获取活动作品列表的总个数(只提供冲顶大赛活动的作品)
 *
 * @author 毛凯
 * @date 2018-7-21
 *
 * @param {Object} options 参数
 * @param {Number} options.pageNum  页码
 * @param {Number} options.pageSize  页容量
 * @param {String} options.state  作品状态
 * @param {String} options.actId  活动id
 * @param {Number} options.userId  用户id
 * @param {Number} options.orderBy  用户id
 * @param {Function} callback 回调函数
 *
 */
YjxActUserProductModel.prototype.getActUserProductByParamCnt = function (options, callback) {
    options.beForCnt = true;
    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getActivityProductList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getActUserProductByParamList(true,options);
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr) {
                console.log('YjxActUserProductModel.prototype.getActivityProductList queryErr: ' + queryErr);
                return callback(queryErr || '查询失败');
            }
            if (!results || results.length<=0){
                return callback(null,0);
            } else{
                return callback(queryErr, results[0].count);
            }
        });
    });
};

/**
 * 获取图片点赞活动的作品信息
 *
 * @author 王俊
 * @date 2018-07-31
 *
 * 注意: 参数可为  option.actId 和 option.userId 或 option.productId, 或 全部传递, 注意: 对应关系
 *
 * @param {{Object}} options
 * @param {Number} [options.actId]         活动 id
 * @param {Number} [options.userId]        用户 id
 * @param {Number} [options.productId]     作品 id
 * @param {Function} callback
 *                      error
 *                      info
 */
YjxActUserProductModel.prototype.getImagePraiseActivityProductInfo = function(options, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductInfo getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = ' SELECT yaup.*, ' +
            '   (SELECT count(0) ' +
            '    FROM yjx.yjx_user_like yul ' +
            '    WHERE yul.del_flg=0 ' +
            '      AND yul.type =10 ' +
            '      AND yul.obj_type = 10 ' +
            '      AND yul.obj_id = yaup.aup_id) AS likePeopleCnt, ' +
            '        ifnull( ' +
            '                 (SELECT sum(yaur.bal_reward) ' +
            '                  FROM yjx.yjx_act_user_reward yaur ' +
            '                  WHERE yaur.aup_id = yaup.aup_id ' +
            '                    AND yaur.r_type = 32 ' +
            '                    AND yaur.bal_flg = 1 ' +
            '                    AND yaur.del_flg = 0 ' +
            '                    AND yaur.state = 10), 0) AS likeReward, ' +
            '        ifnull(ytpu.nickname, (SELECT yu.nickname FROM yjx_user yu WHERE yu.user_id = yaup.user_id AND yu.del_flg=0)) AS authorName, ' +
            '        ifnull(ytpu.profile_photo, (SELECT yu.profile_photo FROM yjx_user yu WHERE yu.user_id = yaup.user_id AND yu.del_flg=0)) AS authorIcon ' +
            ' FROM yjx.yjx_act_user_product yaup ' +
            ' LEFT JOIN yjx.yjx_third_party_user ytpu ON ytpu.del_flg=0 AND ytpu.user_id = yaup.user_id AND ytpu.account_type = 202 '+
            ' WHERE yaup.del_flg=0 ';
        if(options.actId) {
            sql += '   AND yaup.act_id= ' + options.actId;
        }
        if(options.userId) {
            sql += '   AND yaup.user_id = ' + options.userId;
        }
        if(options.productId) {
            sql += '   AND yaup.aup_id = ' + options.productId;
        }
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr) {
                console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductInfo queryErr: ' + queryErr);
                return callback(queryErr || '查询失败');
            }
            return callback(queryErr, results);
        });
    });
};

/**
 * 获取某作品点赞用户列表
 *
 * @author 王俊
 * @date 2018-07-31
 *
 * @param {Boolen} beForCnt                  是否用于获取个数
 * @param {{Object}} options
 * @param {Array} options.productId          作品 id
 * @param {Number} options.pageNum           页码
 * @param {Number} options.pageSize          页容量
 * @param {Number} options.rewardType        10挑战活动奖励，20发放推广码奖励, 21填写推广码奖励, 30首次浏览活动分享页随机红包, 31点赞方奖励, 32被点赞方奖励',
 * @param {Number} [options.withTotalPage]   是否获取总页数
 * @param {Number} [options.orderBy]         排序方式, 1 时间倒序, 2 点赞金额
 */
function sql_getImagePraiseActivityProductLikeUserList(beForCnt, options) {
    options.orderBy = options.orderBy || 1;
    var sql = '';
    if(beForCnt) {
        sql += ' SELECT COUNT(0) AS count ';
    } else {
        sql += ' SELECT ifnull( ' +
        '                 (SELECT ytpu.profile_photo FROM yjx.yjx_third_party_user ytpu WHERE ytpu.del_flg=0 AND ytpu.account_type = 202 AND ytpu.user_id = yu.user_id), ' +
        '                  yu.profile_photo) AS profilePhoto, ' +  // ifnull 取头像
        '               ifnull(' +
        '                  (SELECT ytpu.nickname FROM yjx.yjx_third_party_user ytpu WHERE ytpu.del_flg=0 AND ytpu.account_type = 202 AND ytpu.user_id = yu.user_id), ' +
        '                  yu.nickname) AS nickName, ' +  // ifnull 取昵称
        '        DATE_FORMAT(yul.create_time, "%m-%d %H:%i") AS likeTime, ' +
        '        UNIX_TIMESTAMP(yul.create_time) AS likeTimestamp, ' +
        '        ifnull(yaur.bal_reward, 0) AS rewardAmt ';
    }
    sql +=
        ' FROM yjx.yjx_user yu, ' +
        '      yjx.yjx_user_like yul ' +
        ' LEFT JOIN yjx.yjx_act_user_reward yaur ON yaur.like_id = yul.like_id AND yaur.del_flg=0 AND yaur.state = 10 AND yaur.r_type = ' + options.rewardType + // 左关联取奖励金额
        ' WHERE yul.del_flg =0 ' +
        '   AND yul.type = 10 ' +
        '   AND yul.obj_type = 10 ' +
        '   AND yul.obj_id = ' + options.productId+
        '   AND yu.user_id = yul.user_id ';
    if (!beForCnt) {
        if(options.orderBy === 1) {
            sql += ' ORDER BY yul.create_time DESC ';
        }
        if(options.orderBy === 2) {
            sql += ' ORDER BY yaur.bal_reward ';
        }
        if (typeof options.pageNum !== 'undefined' && options.pageNum !== null &&
            typeof options.pageSize !== 'undefined' && options.pageSize !== null)
        {
            var skipCnt = Number(options.pageNum||'0') * Number(options.pageSize||'0');
            sql += " LIMIT " + skipCnt + "," + Number(options.pageSize||'0');
        }
    }
    return sql;
}
/**
 * 获取某作品点赞用户列表
 *
 * @author 王俊
 * @date 2018-07-31
 *
 * @param {{Object}} options
 * @param {Array} options.productId          作品 id
 * @param {Number} options.pageNum           页码
 * @param {Number} options.pageSize          页容量
 * @param {Number} options.rewardType        10挑战活动奖励，20发放推广码奖励, 21填写推广码奖励, 30首次浏览活动分享页随机红包, 31点赞方奖励, 32被点赞方奖励',
 * @param {Number} [options.withTotalPage]   是否获取总页数
 * @param {Number} [options.orderBy]         排序方式, 1 时间倒序, 2 点赞金额
 * @param {Function} callback
 *                      error
 *                      results
 */
YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList = function(options, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getImagePraiseActivityProductLikeUserList(false, options);
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr) {
                console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList queryErr: ' + queryErr);
                return callback(queryErr || '查询失败');
            }
            return callback(queryErr, results);
        });
    });
};

/**
 * 获取某作品点赞用户列表
 *
 * @author 王俊
 * @date 2018-07-31
 *
 * @param {{Object}} options
 * @param {Array} options.productId          作品 id
 * @param {Number} options.rewardType        10挑战活动奖励，20发放推广码奖励, 21填写推广码奖励, 30首次浏览活动分享页随机红包, 31点赞方奖励, 32被点赞方奖励',
 * @param {Function} callback
 *                      error
 *                      count
 */
YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserListCnt = function(options, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql = sql_getImagePraiseActivityProductLikeUserList(true, options);
        console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList queryErr: ' + queryErr);
                return callback(queryErr || '获取作品点赞人数失败');
            }
            return callback(queryErr, results[0].count);
        });
    });
};



/**
 * 获取某作品的用户id
 *
 * @author 王俊
 * @date 2018-07-31
 *
 * @param {{Object}} options
 * @param {Array} options.productId          作品 id
 * @param {Function} callback
 *                      error
 *                      count
 */
YjxActUserProductModel.prototype.getUserIdByUserProductId = function(options, callback) {
    pool.pool.getConnection(function(getConErr, connection) {
        if(getConErr) {
            console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList getConErr: ' + getConErr);
            return callback(getConErr, null);
        }
        var sql ="	SELECT	" +
                "	  yaup.user_id AS `id`	" +
                "	FROM	" +
                "	  yjx.yjx_act_user_product yaup	" +
                "	WHERE yaup.del_flg = 0	" +
                "	  AND yaup.aup_id = "+options.productId+"	" +
                "	  AND yaup.state = 30	" +
                "	  AND yaup.type = 20	" ;
            console.log(sql);
        connection.query(sql, function(queryErr, results) {
            connection.release();
            if(queryErr || !results || results.length <=0) {
                console.log('YjxActUserProductModel.prototype.getImagePraiseActivityProductLikeUserList queryErr: ' + queryErr);
                return callback(queryErr || '获取作品点赞人数失败');
            }
            return callback(queryErr, results[0].id);
        });
    });
};


module.exports = YjxActUserProductModel;

